package com.example.consulconsumer.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@Slf4j
public class ConsumerController {
    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("{name}/{api}")
    public String test(@PathVariable("name" ) String name, @PathVariable("api") String api){


        List<ServiceInstance> instances = this.discoveryClient.getInstances(name);//"producer01"
        log.info(instances.toString());
        ServiceInstance serviceInstance = instances.get(0);
        URI uri = serviceInstance.getUri();
        String targetUrl = uri +"/"+api;// "/producer01";
        log.info(targetUrl);
        String rst = restTemplate.getForObject( targetUrl, String.class );

        return "consumer : " + rst;
    }
}
